package com.atxyj.srb.base.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author: xyj
 * @date: 2021/7/22
 *  解决对象存储序列化问题
 */
@Configuration
public class RedisConfig {

    /**
     * redisTemplate优化，提高redis连接效率
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        //首先解决key的序列化方式(默认情况下redis的key和value用的是jdk的序列化，效率低)
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);

        //解决value的序列化方式

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        //解决Jackson2无法反序列LocalDateTime的问题
        ObjectMapper objectMapper = new ObjectMapper();
        //记住序列号的类型(把当前实例的序列号类型也存入到最终的序列化结果中)
        //将当前对象的数据类型也传入序列号的结果字符串中
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
        //禁用原本的序列化方案
        objectMapper.disable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);
        objectMapper.registerModule(new JavaTimeModule());
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //设置连接池工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //【注意】：做序列号的时候需要把序列号的类型也要序列号进去，方便反序列化指定具体对象类型
        return redisTemplate;
    }
}
